<template>
  <div class="monitor-fullscreen">
    <div class="video-container">
      <div class="grid-container">
        <div
          class="grid-item"
          v-for="(item, index) in vieoIndexArray"
          :key="index"
          :class="[
            'grid-item',
            item && videoIsChooseCurrentIndex === index && item.isSelect
              ? 'active'
              : 'unactive',
          ]"
        >
          <div class="panel" v-if="item && item.rtcIP">
            <VideoPlayer
              v-if="item && item.rtcIP"
              :id="item.videoID + '-' + index"
              ref="videoPlayerRef"
              :src="item.rtcIP"
            />
          </div>
          <div
            v-else
            class="empty-text"
            @click.stop="chooseItem($event, index)"
          >
            点击此处再选择右侧列表监控设备
          </div>
          <div class="control-box" v-if="item && item.rtcIP" @click.stop>
            <el-checkbox
              :model-value="currentCheckIndex == index && item.checked"
              size="large"
              v-if="item && item.model"
              title="云台控制"
              @change="change($event, item, index)"
            />
            <img
              class="fullscreeen"
              :src="requireImgUrl('image', '全屏')"
              alt=""
              @click.stop="fullscreeen(item.videoID + '-' + index)"
            />
            <img
              class="close"
              :src="requireImgUrl('image', '小屏_关闭')"
              alt=""
              @click.stop="close(index)"
            />
          </div>
        </div>
      </div>
      <div class="videoinfo-container">
        <div class="video-list">
          <div class="search-box">
            <input
              placeholder="请输入关键字"
              type="text"
              v-model="filterText"
            />
          </div>
          <div class="list-detail">
            <el-tree
              ref="treeRef"
              empty-text="无此数据"
              :data="Treedata"
              :filter-node-method="filterNode"
              render-after-expand
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <div
                  class="custom-tree-node custom"
                  :class="
                    data.type !== '0' && data.status == '0' ? 'outline' : ''
                  "
                >
                  <div class="empty-box" v-if="node.label == '暂无数据'">
                    <el-empty :image-size="100" description="暂无数据" />
                  </div>
                  <div
                    v-else
                    class="lefttitle"
                    :class="
                      data.children && data.children.length > 0 ? 'parent' : ''
                    "
                  >
                    {{ node.label }}
                  </div>
                  <div
                    class="rightstatus"
                    v-if="data.type !== '0' && data.status == '0'"
                  >
                    离线
                  </div>
                  <div class="rightstatus local" v-if="data.type == '0'">
                    位置
                  </div>
                  <div
                    class="rightstatus eq"
                    v-if="data.type !== '0' && data.status == '1'"
                  >
                    在线
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
        <div class="video-control">
          <Gimbal />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, toRefs, watch, onUnmounted, nextTick, onMounted } from "vue";
import { ElTree } from "element-plus";
import { UseScreenEqTree } from "@/stores/screen/equipementTree";
import { ElMessage } from "element-plus";
import {
  getRtsp,
  executeGatewayControl,
  getEqControlItem,
} from "@/api/screen/equipment";
import { requireImgUrl } from "@/utils/localurl/metaUrl";
import emits from "@/utils/emits";
// 条件限制
const treeRef = ref<InstanceType<typeof ElTree>>();
interface videoObject {
  videoID: string;
  status: string;
  rtcIP: null;
  title: string;
  isSelect: Boolean;
  model: Boolean;
  checked: Boolean;
}
interface Tree {
  label: string;
  children?: Tree[];
}
// key value 值
const defaultProps = {
  children: "children",
  label: "label",
};
// model属性
const videoPlayerRef = ref();
const Treedata = ref([]);
const vieoIndexArray = ref(new Array(4));
const videoIsChooseCurrentIndex = ref(0);
const filterText = ref("");
const { data } = toRefs(UseScreenEqTree());
// 获取视频流地址接口
const getVideoUrl = async (videoID: string) => {
  let res = (await getRtsp(videoID)) as any;
  if (res.code == 200) {
    return res.data;
  }
};
// 节点选择
const handleNodeClick = async (tree: any) => {
  if (videoIsChooseCurrentIndex.value == -1) {
    return;
  } else {
    if (
      JSON.stringify(vieoIndexArray.value) !== "[null]" &&
      tree.id &&
      tree.type !== "0"
    ) {
      if (tree.status !== "0") {
        console.log(tree.id);
        if (tree.model && (tree.model == "球机" || tree.model == "鹰眼")) {
          try {
            ElMessage({
              message: "选择设备-执行预览云台",
              type: "success",
            });
            console.log("执行云台监控");
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].videoID =
              tree.id;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].title =
              tree.label;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].status =
              tree.status;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].isSelect = false;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].model = true;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].checked = false;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].rtcIP = await getVideoUrl(tree.id);
            videoIsChooseCurrentIndex.value = -1;
          } catch {
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].videoID = "";
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].title = "";
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].isSelect = true;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].rtcIP = null;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].model = true;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].checked = false;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].status = 0;
            videoIsChooseCurrentIndex.value = -1;
          }
        } else {
          try {
            ElMessage({
              message: "选择设备-执行预览监控",
              type: "success",
            });
            console.log("执行普通监控");
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].videoID =
              tree.id;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].title =
              tree.label;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].status =
              tree.status;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].isSelect = false;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].model = false;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].checked = false;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].rtcIP = await getVideoUrl(tree.id);
            videoIsChooseCurrentIndex.value = -1;
          } catch {
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].videoID = "";
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].title = "";
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].isSelect = true;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].rtcIP = null;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].model = false;
            vieoIndexArray.value[
              videoIsChooseCurrentIndex.value
            ].checked = false;
            vieoIndexArray.value[videoIsChooseCurrentIndex.value].status = 0;
            videoIsChooseCurrentIndex.value = -1;
          }
        }
      } else {
        ElMessage({
          message: "设备离线",
          type: "error",
        });
        videoIsChooseCurrentIndex.value = -1;
      }
    }
  }
};

// 选择方框
const chooseItem = ($event, index: number) => {
  console.log(videoIsChooseCurrentIndex.value, index);
  $event.stopPropagation();
  if (videoIsChooseCurrentIndex.value == index) {
    console.log("执行return");
    return;
  } else {
    videoIsChooseCurrentIndex.value = index;
    console.log("执行选择");
    let funObj: videoObject = {
      videoID: "",
      status: "",
      rtcIP: null,
      title: "",
      isSelect: true,
      model: false,
      checked: false,
    };
    vieoIndexArray.value[index] = funObj;
  }
};
// 全屏
const fullscreeen = (id) => {
  nextTick(() => {
    let elVideo = document.getElementById(id) as any;
    if (elVideo) {
      if (elVideo.requestFullscreen) {
        elVideo.requestFullscreen();
      } else if (elVideo.mozRequestFullScreen) {
        elVideo.mozRequestFullScreen();
      } else if (elVideo.webkitRequestFullscreen) {
        elVideo.webkitRequestFullscreen();
      } else if (elVideo.msRequestFullscreen) {
        elVideo.msRequestFullscreen();
      }
    }
  });
};
// 关闭当前视频
const close = (index) => {
  vieoIndexArray.value[index] = "";
};

// 过滤
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};
// 控制项item
const controlItem = ref({
  controlId: "",
  equipmentId: "",
});
const field = ref("");
// 获取网关控制项
const GETCONTROLITEM = async (id) => {
  if (id) {
    console.log("切换id==============================>", id);
    let res = (await getEqControlItem(id)) as any;
    if (res.code == 200) {
      controlItem.value = {
        controlId: res.data[0].id,
        equipmentId: id,
      };
      field.value = res.data[0].execParams[0].field;
    }
  }
};
// 执行设备控制
const controlEQ = async (command) => {
  let execParams = {};
  execParams[field.value] = command;
  let queryForm = {
    controlId: controlItem.value.controlId,
    equipmentId: controlItem.value.equipmentId,
    execParams,
  };
  let res = (await executeGatewayControl(
    controlItem.value.controlId,
    queryForm
  )) as any;
  if (res.code === 200) {
  }
};
// 当前勾选的checked
const currentCheckIndex = ref(-1);
const change = ($event, item, index) => {
  if (!item.checked) {
    vieoIndexArray.value.forEach((c) => {
      c.checked = false;
    });
    currentCheckIndex.value = index;
    item.checked = true;
    ElMessage({
      message: "勾选",
      type: "info",
    });
    // 获取网关控制项
    GETCONTROLITEM(item.videoID);
  } else {
    currentCheckIndex.value = -1;
    item.checked = false;
    ElMessage({
      message: "取消勾选",
      type: "info",
    });
  }
};
onMounted(() => {
  nextTick(() => {
    let funObj: videoObject = {
      videoID: "",
      status: "",
      rtcIP: null,
      title: "",
      isSelect: true,
      model: false,
      checked: false,
    };
    vieoIndexArray.value[0] = funObj;
    emits.on("HANDEL_GIMBAL", (str) => {
      if (controlItem.value.equipmentId && controlItem.value.controlId) {
        switch (str) {
          case "上":
            controlEQ("UP");
            break;
          case "下":
            controlEQ("DOWN");
            break;
          case "左":
            controlEQ("LEFT");
            break;
          case "右":
            controlEQ("RIGHT");
            break;
          case "减焦距":
            controlEQ("ZOOM_OUT");
            break;
          case "加焦距":
            controlEQ("ZOOM_IN");
            break;
          default:
            break;
        }
      } else {
        ElMessage({
          message: "未勾选云台设备",
          type: "warning",
        });
      }
    });
  });
});
// 自动过滤搜索
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
// 监听表单变化
watch(
  () => data.value,
  (newVal) => {
    if (newVal.length > 0) {
      Treedata.value = newVal;
    } else {
      Treedata.value = [
        {
          label: "暂无数据",
        },
      ];
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
// 卸载断开所有连接
onUnmounted(() => {
  vieoIndexArray.value = [];
  controlItem.value = {
    controlId: "",
    equipmentId: "",
  };
  emits.emit("CLOSE_VIDEO");
  emits.off("HANDEL_GIMBAL");
  console.log(
    "====================================================================清空监控数组===================================================================="
  );
});
</script>
<style lang="scss" scoped>
.monitor-fullscreen {
  margin-top: 5vh;
  width: 100%;
  height: 100%;

  .video-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;

    .grid-container {
      width: 75%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      align-content: space-between;
      justify-content: space-between;

      .grid-item {
        width: 49.5%;
        height: 49.2%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        position: relative;
        background-color: rgba(4, 19, 31, 1);
        border: 1px solid transparent;
        opacity: 1;
        color: #999999;
        cursor: pointer;

        .empty-text {
          padding: 100px;
          box-sizing: border-box;
        }

        .control-box {
          width: 15%;
          height: 30px;
          position: absolute;
          top: 0;
          right: 0;
          background-color: rgba(0, 0, 0, 0.5);
          z-index: 2;
          display: flex;
          align-items: center;
          justify-content: space-around;
        }

        &.active {
          border: 1px solid rgba(38, 190, 255, 1);
        }

        &.unactive {
          border: 1px solid transparent;
        }

        .panel {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .videoinfo-container {
    width: 24%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: column;

    .video-list {
      width: 100%;
      height: 64%;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: rgba(4, 19, 31, 1);

      .search-box {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        width: 80%;
        height: 32px;
        background: rgba(12, 34, 41, 0.68);
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
        border: 1px solid rgba(38, 190, 255, 1);
        margin-bottom: 10px;

        input {
          width: 85%;
          height: 100%;
          border: none;
          outline: none;
          background-color: rgba(8, 31, 48, 1);
          color: white;
          text-indent: 1em;
        }
      }

      .list-detail {
        width: 100%;
        height: calc(100% - 32px);

        // 溢出
        overflow-y: auto;
        scrollbar-width: none;
        cursor: pointer;
        -ms-overflow-style: none;

        &::-webkit-scrollbar {
          display: none;
          /* Chrome Safari */
        }

        .custom {
          width: 100%;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .empty-box {
            margin-top: 200px;
            width: 100%;
            height: 200px;
          }

          &.outline {
            color: rgba(153, 153, 153, 1);
          }

          .parent {
            color: rgba(38, 190, 255, 1);
          }

          .rightstatus {
            width: 50px;
            height: 25px;
            background-color: rgba(173, 228, 228, 0.24);
            border-radius: 2px 2px 2px 2px;
            font-size: 12px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            color: rgba(173, 228, 228, 1);
            display: flex;
            align-items: center;
            justify-content: center;

            &.eq {
              background-color: rgba(173, 228, 228, 0.24);
              color: rgba(173, 228, 228, 1);
            }

            &.local {
              background-color: rgba(173, 228, 228, 0.24);
              color: rgba(173, 228, 228, 1);
            }
          }
        }
      }
    }

    .video-control {
      width: 100%;
      height: 35%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: rgba(4, 19, 31, 1);
    }
  }

  @keyframes animatedgradient {
    0% {
      background-position: 0% 50%;
    }

    50% {
      background-position: 100% 50%;
    }

    100% {
      background-position: 0% 50%;
    }
  }
}
</style>
